﻿using Ec.NETCoreFramework.Common.Core;
using Ec.NETCoreFramework.Common.Core.Helpers;
using Ec.NETCoreFramework.Common.MQ;
using Ec.NETCoreFramework.Common.Core.Utilities;
using Ec.NETCoreFramework.Common.Core.Serializer;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Threading;
using System.Diagnostics;
using Ec.NETCoreFramework.Common;
using Ec.NETCoreFramework.Common.Plug.Core;
using Ec.NETCoreFramework.Common.Clients;

namespace MQ_WechatMedia
{
    /// <summary>
    /// 审批media转换成url
    /// </summary>
    public class ApprovalMedia : IMedia
    {
        private ConsumeConfig _consumeConfig;
        private string logTitle = "ApprovalMedia";
        private RequestAppSecret _appSecret;
        private string _SoftwareVersion = string.Empty;
        public ApprovalMedia(RequestAppSecret appSecret, ConsumeConfig consumeConfig)
        {
            _appSecret = appSecret;
            _SoftwareVersion = AppsettingsHelper.app(new string[] { "SoftwareVersion" });
            _consumeConfig = consumeConfig;
        }
        public  async Task Excute(Dictionary<string,object> dic)
        {
            var limit = 500;
            var stopwatch = new Stopwatch();
            stopwatch.Start();
            try
            {
                while (true)
                {
                    //拉数据
                    var list = await PullData(limit);
                    if (list == null || list.Count == 0)
                    {
                        Console.WriteLine($"【{_consumeConfig.Domain}-{logTitle}】没有拉取到数据哟");
                        break;
                    }
                    foreach (var item in list)
                    {
                        //上传media
                        await GetMediaUrl(item);
                    }

                    //推数据
                    await Push(list);

                    if (list.Count < limit)
                    {
                        Console.WriteLine($"【{_consumeConfig.Domain}-{logTitle}-{_SoftwareVersion}】此次执行结束，耗时{stopwatch.ElapsedMilliseconds}ms");
                        break;
                    }
                    Thread.Sleep(1000);
                }
                stopwatch.Stop();
            }
            catch (Exception ex)
            {

                if (stopwatch.IsRunning)
                {
                    stopwatch.Stop();
                }
                Console.WriteLine($"【{_consumeConfig.Domain}-{logTitle}】:{ex.Message}");
            }
        }
        /// <summary>
        /// 接数据
        /// </summary>
        /// <returns></returns>
        private async Task<List<JournalMediaOutput>> PullData(int limit)
        {
            var dic = new Dictionary<string, object>()
            {
                {"limit",limit.ToString() }
            };
            var result = await new ApiRequestClient(_appSecret).
                GetResponse<List<JournalMediaOutput>>(_consumeConfig.Domain,
                "wxgroup.oa.approval.filemedia.waitsync.get", dic);
            if (result.Success)
            {
                var ret = (IResponse<List<JournalMediaOutput>>)result;
                return (ret.Content);
            }
            return null;

        }
        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private async Task GetMediaUrl(JournalMediaOutput mediaOutput)
        {
            var dic = new Dictionary<string, object>()
            {
                {"fk_id",mediaOutput.fk_id.ToString() },
                {"fk_flag",mediaOutput.fk_flag.ToString() },
                {"db_id",mediaOutput.db_id.ToString() },
                {"media_id",mediaOutput.media_id }
            };
            var result = await new ApiRequestClient(_appSecret).
            GetResponse<JObject>(_consumeConfig.WechatDomain,
            "uploadmedia", dic, "/wx/approval/media/url/get", new Dictionary<string, string>() {{"api-version","2.0" }, { "version", _SoftwareVersion } }, 10000);
            mediaOutput.remote_file_url = string.Empty;
            if (result.Success)
            {
                var ret = ((IResponse<JObject>)result).Content;
                if (ret.ContainsKey("path"))
                {
                    mediaOutput.remote_file_url = Utils.ToString(ret["path"]);
                   
                }
                else
                {                    
                    mediaOutput.errorlog = "不含有关键字path";
                }
            }
            else
            {
                mediaOutput.errorlog = result.Message;
            }

        }
        /// <summary>
        /// 推数据
        /// </summary>
        /// <param name="mediaOutputs"></param>
        /// <returns></returns>
        private async Task Push(List<JournalMediaOutput> mediaOutputs)
        {

            StringBuilder stringBuilder = new StringBuilder();
            foreach (var item in mediaOutputs)
            {
                if (item.errorlog == null)
                {
                    item.errorlog = string.Empty;
                }
                item.media_id = string.Empty;
                stringBuilder.AppendLine($"<material>{item.ToXml()}</material>");
            }
            var dic = new Dictionary<string, object>()
            {
                {"content",($"<root>{stringBuilder.ToString()}</root>").SafeString() }
            };
            var result = await new ApiRequestClient(_appSecret).
        PostBinary<JObject>(_consumeConfig.Domain,
        "wxgroup.oa.approval.filemedia.sync", dic);
            if (!result.Success)
            {
                Console.WriteLine($"【{logTitle}】:{result.Message};{dic.ToLinkString()}");
            }

        }
    }

}
